package servlet;

import entity.Data;
import net.sf.json.JSONArray;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 石小俊
 */
@WebServlet("/query")
public class QueryServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter out = resp.getWriter();
        String spell = req.getParameter("spell");
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<Data> datas = new ArrayList<>();
        try {
            // 根据主键查询员工信息
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/ajax?useUnicode=true&characterEncoding=utf-8", "root", "root");
            String sql = new StringBuffer()
                    .append(" select spell,message ")
                    .append(" from t_data ")
                    .append(" where spell like ? ")
                    .append(" or message like ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setString(1, "%" + spell + "%");
            ps.setString(2, "%" + spell + "%");
            rs = ps.executeQuery();
            while (rs.next()) {
                Data data = new Data();
                data.setSpell(rs.getString("spell"));
                data.setMessage(rs.getString("message"));
                datas.add(data);
            }

            // 调用JSON工具类,将集合转换成JSON数组
            JSONArray jsonArray = JSONArray.fromObject(datas);
            // 将JSON数组格式的字符串返回到JavaScript中
            out.println(jsonArray.toString());
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("未找到驱动");
        } catch (SQLException e) {
            throw new RuntimeException("数据访问异常");
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    throw new RuntimeException("释放连接失败");
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    throw new RuntimeException("释放状态集失败");
                }
            }
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    throw new RuntimeException("释放结果集失败");
                }
            }
        }
    }
}
